//
//  WeChatViewController.m
//  BaseAPP
//
//  Created by Evisu on 16/12/8.
//  Copyright © 2016年 evisum. All rights reserved.
//

#import "WeChatViewController.h"
#import "DMSearchBar.h"
#import "DMSearchDetailView.h"
#import "SearchViewController.h"
#import "DMConversationCell.h"
#import "EMClient.h"
#import "MessageViewController.h"
#import "ListView.h"
#import "AddFriendViewController.h"
#import "AppDelegate.h"

@interface WeChatViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, DMSearchDetailViewDelegate, listViewDelegate>

@property (nonatomic, strong)UIScrollView *scrollView;

//搜索栏
@property (nonatomic, strong)DMSearchBar *searchBar;

//分割线
@property (nonatomic, strong)UIImageView *lineView;

@property (nonatomic, strong)UITableView *tableView;

//搜索选项页：朋友圈、文章、公众号
@property (nonatomic, strong)DMSearchDetailView *searchDetailView;

@property (nonatomic, strong)NSArray *conversations;

@property (nonatomic, strong)UIView *cover;

//加号菜单View
@property (nonatomic, strong)ListView *ivListView;
@property (nonatomic, strong)NSArray *lists;

//右上角加号弹出View的布局
@property (nonatomic, strong)SDAutoLayoutModel *listViewLayoutModel;

@end

@implementation WeChatViewController

#pragma mark - 懒加载
- (UISearchBar *)searchBar {

    if (!_searchBar) {
        
        _searchBar = [[DMSearchBar alloc] init];

    }
    
    return _searchBar;
}

- (UIImageView *)lineView {

    if (!_lineView) {
        
        _lineView = [[UIImageView alloc] initWithImage:[UIImage imageWithColor:KNAVIGAtiON_SEPARATION_LINE]];
    }
    
    return _lineView;
}

- (DMSearchDetailView *)searchDetailView {

    if (!_searchDetailView) {
        
        _searchDetailView = [[DMSearchDetailView alloc] init];
    }
    
    return _searchDetailView;
}

- (NSArray *)conversations {

    if (!_conversations) {
        
        _conversations = [NSArray array];
    }
    
    return _conversations;
}

- (NSArray *)lists {

    if (!_lists) {
        
        _lists = [NSArray array];
    }
    
    return _lists;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initViews];
    [self layoutViews];
    
    _lists = @[@[@"发起群聊", @"contacts_add_newmessage"], @[@"添加朋友", @"barbuttonicon_addfriends"], @[@"扫一扫", @"contacts_add_scan"], @[@"收付款", @"receipt_payment_icon"]];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.tableView.hidden == YES) {
        
        [self.searchBar becomeFirstResponder];
    }
    
    //tableView contentSize KVO
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    //获取会话列表
    [self fetchAllConversations];
    
    //自动登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(autoLogin) name:KAUTOLOGIN object:nil];
        
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.searchBar resignFirstResponder];
    
    [self.tableView removeObserver:self forKeyPath:@"contentSize" context:nil];
    
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KAUTOLOGIN object:nil];
    
    //隐藏listView
    [self hideListView];
}


/**
 *  添加子控件
 */
- (void)initViews {
    
    __block typeof(self) weakSelf = self;
    
    //导航栏加号按钮
    [self showRightBarButtonWithImageName:@"barbuttonicon_add"];
    self.rightBtnBlock = ^(){
        
        DMLog(@"点击了右边");
        
        if (self.ivListView.selected == YES) {
            
            //收起listView
            [weakSelf hideListView];
        } else {
        
            //显示listView
            //cover
            weakSelf.cover = [[UIView alloc] init];
            weakSelf.cover.backgroundColor = [UIColor clearColor];
            weakSelf.cover.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(hideListView)];
            [weakSelf.cover addGestureRecognizer:tap];
            
            //listView
            weakSelf.ivListView = [[ListView alloc] init];
            weakSelf.ivListView.lists = weakSelf.lists;
            weakSelf.ivListView.delegate = weakSelf;
            weakSelf.ivListView.selected = YES;
            weakSelf.ivListView.userInteractionEnabled = YES;
            [weakSelf.view addSubview:weakSelf.cover];
            [weakSelf.view insertSubview:weakSelf.ivListView atIndex:10];
            
            weakSelf.listViewLayoutModel = weakSelf.ivListView.sd_layout
            .topSpaceToView(weakSelf.view, KSTATUS_AND_NAVIGATION_HEIGHT)
            .rightEqualToView(weakSelf.view)
            .heightIs(193)
            .widthIs(144);
            
            weakSelf.cover.sd_layout
            .topSpaceToView(weakSelf.view, KSTATUS_AND_NAVIGATION_HEIGHT)
            .leftEqualToView(weakSelf.view)
            .rightEqualToView(weakSelf.view)
            .bottomSpaceToView(weakSelf.view, KTABBAR_HEIGHT);
        }
        
        
        
    };
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    
    //搜索栏
    self.searchBar.delegate = self;
    [self.scrollView addSubview:self.searchBar];
    
    //分割线
    [self.scrollView addSubview:self.lineView];

    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.scrollView addSubview:self.tableView];
    
}

/**
 *  布局子控件
 */
- (void)layoutViews {

    self.scrollView.sd_layout
    .topSpaceToView(self.view, KSTATUS_AND_NAVIGATION_HEIGHT)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomSpaceToView(self.view, KTABBAR_HEIGHT);
    
    self.searchBar.sd_layout
    .topSpaceToView(self.scrollView, 0)
    .leftEqualToView(self.scrollView)
    .rightEqualToView(self.scrollView)
    .heightIs(KSEARCHBAR_HEIGHT);

    self.lineView.sd_layout
    .topSpaceToView(self.searchBar, 0)
    .leftEqualToView(self.searchBar)
    .rightEqualToView(self.searchBar)
    .heightIs(1);
    
    self.tableView.sd_layout
    .topSpaceToView(self.searchBar, 1)
    .leftEqualToView(self.scrollView)
    .rightEqualToView(self.scrollView);
    
}

#pragma mark - UISearchBar  Delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    //显示取消按钮
    self.searchBar.showsCancelButton = YES;
    
    UIButton *cancleButton = [searchBar valueForKey:@"cancelButton"];
    [cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancleButton setTitleColor:HEXColor(@"65C96B") forState:UIControlStateNormal];
    cancleButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
    
    //搜索栏往上移
    [UIView animateWithDuration:0.3 animations:^{
        
        self.scrollView.top_sd = KSTATUSBAR_HEIGHT;
        self.navigationController.tabBarController.tabBar.hidden = YES;
        
    }];
    
    //隐藏导航栏
    [self hideNavigationBar];
    
    self.tableView.hidden = YES;
    
    //搜索栏不可滑动
    self.scrollView.contentSize = CGSizeMake(self.view.width_sd, 1);
//    self.scrollView.backgroundColor = KBACKGROUND_COLOR;
    
    //搜索选项页：朋友圈、文章、公众号
    self.searchDetailView.searchDelegate = self;
    self.searchDetailView.contentSize = CGSizeMake(self.view.width_sd, self.view.height_sd+1);
    self.searchDetailView.frame = CGRectMake(0, 45, self.view.width_sd, self.view.height_sd);
    
    [self.scrollView addSubview:self.searchDetailView];
    
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

    searchBar.showsCancelButton = NO;
    [searchBar resignFirstResponder];
    
    //搜索栏往下移
    [UIView animateWithDuration:0.3 animations:^{
        
        self.scrollView.top_sd = KSTATUS_AND_NAVIGATION_HEIGHT;
        self.navigationController.tabBarController.tabBar.hidden = NO;
    }];
    
    //显示导航栏
    [self showNavigationBar];
    
    //搜索栏恢复滑动
    self.scrollView.contentSize = CGSizeMake(self.view.width_sd, self.tableView.height_sd + KTABBAR_HEIGHT);
    self.scrollView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.hidden = NO;
    
    //移除搜索选项页
    [self.searchDetailView removeFromSuperview];
}

#pragma mark - tableView
#pragma mark tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.conversations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *reusedId = @"wechat";
    
    DMConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:reusedId];
    
    if (!cell) {
        
        cell = [[DMConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedId];
        cell.textLabel.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    }
    
    EMConversation *conversation = self.conversations[indexPath.row];
    
    cell.conversation = conversation;
    
    return cell;
}

#pragma mark tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 66;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    DMLog(@"did selected cell for row");
    
    EMConversation *conversation = self.conversations[indexPath.row];
    
    DMConversationCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
    
    MessageViewController *messageVC = [[MessageViewController alloc] init];
    messageVC.conversation = conversation;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:messageVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}

#pragma mark - 搜索页 delegate
- (void)DMSearchDetailViewDidClickedBtnTag:(NSInteger)type {

    SearchViewController *SnsVC = [[SearchViewController alloc] init];
    SnsVC.type = type;
    SnsVC.cancelBlock = ^(){
        [self searchBarCancelButtonClicked:self.searchBar];
    };
    [self.navigationController pushViewController:SnsVC animated:YES];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {

    CGSize size = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue];
    
    size.height = size.height < (self.view.height_sd-KSTATUS_AND_NAVIGATION_HEIGHT-KSEARCHBAR_HEIGHT-KTABBAR_HEIGHT)?(self.view.height_sd-KSTATUS_AND_NAVIGATION_HEIGHT-KSEARCHBAR_HEIGHT-KTABBAR_HEIGHT):size.height;
    
    self.tableView.height_sd = size.height;
    self.scrollView.contentSize = CGSizeMake(self.view.width_sd, self.tableView.height_sd + KTABBAR_HEIGHT);
}


#pragma mark 自动登录
- (void)autoLogin {

    DMLog(@"自动登录");
}

#pragma mark 获取会话列表
- (void)fetchAllConversations {

    dispatch_async(KQUEUE_GLOBAL, ^{
        
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        
        if (conversations.count > 0) {
            
            dispatch_async(KQUEUE_MAIN, ^{
                
                _conversations = conversations;
                
                [self.tableView reloadData];
            });
        }
    });
    
}

#pragma mark 隐藏菜单View
- (void)hideListView {
    
    if (self.cover) {
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.ivListView.alpha = 0;
            self.listViewLayoutModel.heightIs(20);
            self.listViewLayoutModel.widthIs(100);
            [self.view layoutIfNeeded];
            
        } completion:^(BOOL finished) {
            
            self.ivListView.selected = NO;
            [self.cover removeFromSuperview];
            [self.ivListView removeFromSuperview];
        }];
    }
    
}

#pragma mark 右上角加号ListView选中代理
- (void)listViewDidClickedIndex:(long)tag {

    DMLog(@"%ld", tag);
    
    NSArray *model = _lists[tag];
    
    BaseViewController *VC = nil;
    
    switch (tag) {
            
        case 0:
            VC = [[BaseViewController alloc] init];
            break;
            
        case 1:
            VC = [[AddFriendViewController alloc] init];
            break;
            
        case 2:
            VC = [[BaseViewController alloc] init];
            break;
            
        case 3:
            VC = [[BaseViewController alloc] init];
            break;
            
        default:
            break;
    }
    
    VC.title = model.firstObject;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}


@end
